package com.kws.merchant.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.util.concurrent.AtomicDouble;
import com.kws.common.security.auth.AuthLogic;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.service.TokenService;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.po.ItemPo;
import com.kws.merchant.domain.po.PowerStationPo;
import com.kws.merchant.domain.po.SchemePo;
import com.kws.merchant.domain.vo.ItemVo;
import com.kws.merchant.domain.vo.PowerStationVo;
import com.kws.merchant.mapper.ItemMapper;
import com.kws.merchant.service.*;
import com.kws.merchant.util.TimeUtil;
import com.kws.system.api.domain.SysUser;
import com.kws.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 报价-项目(Item)表服务实现类
 *
 * @author yxy
 * @since 2024-10-24 14:46:59
 */
@Service("itemService")
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements ItemService {

    @Autowired
    private ItemSchemeService itemSchemeService;
    @Autowired
    private ItemSchemeInfoService itemSchemeInfoService;
    @Autowired
    private ItemDeviceService itemDeviceService;
    @Autowired
    private ItemSchemeMerchantService itemSchemeMerchantService;
    @Autowired
    private ItemUserSchemeService itemUserSchemeService;

    /**
     * 分页查询列表
     */
    @Override
    public Page<Item> pageList(ItemPo itemPo) {
        Page<Item> page = new Page<>(itemPo.getPageSize(), itemPo.getTotalPage());
        LambdaQueryWrapper<Item> queryWrapper = Wrappers.<Item>lambdaQuery();
        String name = itemPo.getName();//名称
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.eq(Item::getItemName, name);
        }
        return this.page(page, queryWrapper);
    }

    /**
     * 项目报价处理
     *
     * @param itemSchemes
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addItemScheme(List<ItemScheme> itemSchemes) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        ItemSchemeMerchant itemSchemeMerchant = null;
        if (itemSchemes.size() != 0) {
            Long schemeId = itemSchemes.get(0).getSchemeId();
           /* OnlineInquiryEntity inquiryEntity = onlineInquiryService.getById(schemeId);
            if (ObjectUtils.isEmpty(inquiryEntity)) {
                throw new RuntimeException("用户方案为空，无法报价，请联系用户添加方案！！");
            }*/
            ItemUserSchemeEntity userSchemeEntity = itemUserSchemeService.getBySchemeId(schemeId);
            if (ObjectUtils.isEmpty(userSchemeEntity)) {
                throw new RuntimeException("没有该方案信息");
            }
            int days = TimeUtil.getDays(new Date(), userSchemeEntity.getDeadlineTime());
            if (days<0){
                throw new RuntimeException("方案已截止报价");
            }
            itemSchemeMerchant = itemSchemeMerchantService.getOne(Wrappers.<ItemSchemeMerchant>lambdaQuery().eq(ItemSchemeMerchant::getMerchantId, sysUser.getCompanyId()).eq(ItemSchemeMerchant::getSchemeId, schemeId));
            if (ObjectUtils.isEmpty(itemSchemeMerchant)) {
                throw new RuntimeException("用户方案为空！！");
            }
            if (itemSchemeMerchant.getStatus() != 1) {
                throw new RuntimeException("当前状态不能报价");
            }
        }
        AtomicDouble price = new AtomicDouble();
        itemSchemes.forEach(x -> {
            //生成一个共有id
            Long fileId = (long) Math.abs(UUID.randomUUID().hashCode());
            x.setId(fileId);
            List<ItemSchemeInfo> itemSchemeInfos = x.getItemSchemeInfos();
            AtomicDouble atomicDouble = new AtomicDouble();
            itemSchemeInfos.stream().forEach(y -> {
                y.setItemSchemeId(fileId);
                atomicDouble.getAndAdd(y.getPrice().doubleValue());
            });
            itemSchemeInfoService.saveBatch(itemSchemeInfos);
            //总价
            x.setItemSchemePrice(atomicDouble.get());
            x.setMerchantId(sysUser.getCompanyId());
            itemSchemeService.save(x);
            price.getAndAdd(atomicDouble.get());
        });
        //修改商家关联表状态
        itemSchemeMerchant.setPrice(new BigDecimal(price.get()));
        itemSchemeMerchant.setStatus(0);
        return itemSchemeMerchantService.updateById(itemSchemeMerchant);
    }

    /**
     * 报价查看
     *
     * @return
     */
    @Override
    public ItemVo schemeDetailById(SchemePo schemePo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        //商家赋值当前商家id查询，用户带入商家id查询
        if (sysUser.getCompanyId() != null) {
            schemePo.setMerchantId(sysUser.getCompanyId());
        }
        Long schemeId = schemePo.getSchemeId();
        //查询用户方案
        ItemUserSchemeEntity userSchemeEntity = itemUserSchemeService.getBySchemeId(schemeId);
        if (ObjectUtils.isEmpty(userSchemeEntity)) {
            throw new RuntimeException("没有该方案信息");
        }
        String schemeFile = userSchemeEntity.getSchemeFile();
        //查询报价明细
        List<ItemScheme> itemSchemes = itemSchemeService.listByItemId(schemeId, sysUser.getCompanyId());
        //根据报价明细id查询单项报价
        itemSchemes.forEach(x -> {
            List<ItemSchemeInfo> itemSchemeInfos = itemSchemeInfoService.listBySchemeId(x.getId());
            x.setItemSchemeInfos(itemSchemeInfos);
        });
        ItemVo itemVo = new ItemVo();
        itemVo.setSchemeFile(schemeFile);
        itemVo.setItemSchemes(itemSchemes);
        return itemVo;
    }

    /**
     * 根据设备名称获取设备信息
     *
     * @param itemName
     * @return
     */
    @Override
    public Item getByName(String itemName) {
        return this.getOne(Wrappers.<Item>lambdaQuery().eq(Item::getItemName, itemName));
    }

    /**
     * 根据项目查询设备
     *
     * @param itemId
     * @return
     */
    @Override
    public List<Device> listByItemId(Long itemId) {
        List<Device> list = itemDeviceService.listByItemId(itemId);
        return list;
    }

    /**
     * 查询商家项目
     *
     * @param companyId
     * @return
     */
    @Override
    public List<Item> listByMerchantId(Long companyId) {
        return this.list(Wrappers.<Item>lambdaQuery().eq(Item::getMerchantId, companyId));
    }

    /**
     * 商家项目列表
     *
     * @return
     */
    @Override
    public List<Item> listByMerchant() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        return this.list(Wrappers.<Item>lambdaQuery().eq(Item::getMerchantId, companyId));
    }

    /**
     * 根据项目名称查询商家项目
     *
     * @param itemName
     * @return
     */
    @Override
    public Item getByMerchantName(String itemName) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        return this.getOne(Wrappers.<Item>lambdaQuery().eq(Item::getItemName, itemName).eq(Item::getMerchantId, companyId));
    }

//    /**
//     * 获取我的电站列表
//     * @param powerStationPo
//     * @return
//     */
//    @Override
//    public Page<PowerStationVo> getPowerStationList(PowerStationPo powerStationPo) {
//        Long userId = SecurityUtils.getUserId();
//        powerStationPo.setPageSize((powerStationPo.getPageSize() - 1) * powerStationPo.getTotalPage());
//        LambdaQueryWrapper<Item> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(Item::getUserId, userId);
//        wrapper.eq(Item::getItemName, powerStationPo.getItemName());
//        long count = this.count(wrapper);
//        Page<PowerStationVo> page = new Page<>(powerStationPo.getPageSize(), powerStationPo.getTotalPage(), count);
//        if (count > 0) {
//            List<PowerStationVo> powerStationList = baseMapper.getPowerStationList(powerStationPo.getItemName(), userId
//                    , powerStationPo.getTotalPage(), powerStationPo.getTotalPage());
//            page.setRecords(powerStationList);
//        }
//        return page;
//    }
//
//    /**
//     * 获取我的电站项目名称列表
//     * @return
//     */
//    @Override
//    public List<String> getPowerStationNameList() {
//        LambdaQueryWrapper<Item> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(Item::getUserId, SecurityUtils.getUserId());
//        List<Item> list = this.list(wrapper);
//        return list.stream().map(Item::getItemName)
//                .filter(Objects::nonNull)
//                .filter(name -> !name.trim().isEmpty())
//                .distinct().collect(Collectors.toList());
//    }
//
//    @Override
//    public Object getPowerStationInfo(PowerStationPo powerStationPo) {
//
//        return null;
//    }


}
